package link.xieyu.wechat.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.core.util.XmlUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import link.xieyu.config.CommonProperties;
import link.xieyu.service.AppClickService;
import link.xieyu.wechat.Constant;
import link.xieyu.wechat.WechatModule;
import link.xieyu.wechat.entity.Button;
import link.xieyu.wechat.entity.EventTypeEnums;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.Collator;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static link.xieyu.wechat.Constant.TOKEN;

/**
 * @author xieyu
 */
@Controller
@RequestMapping("/app/wx")
@RequiredArgsConstructor
public class WxController {
    private final WechatModule wechatModule;
    private final AppClickService appClickService;
    public static final String GET_ACCESS_TOKEN ="https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code" .replace("APPID", Constant.APP_ID).replace("SECRET", Constant.APP_SECRET);

    public static final String url =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect"
                    .replace("APPID", Constant.APP_ID)
                    //授权后重定向的回调链接地址， 请使用 urlEncode 对链接进行处理
//                .replace("REDIRECT_URI", redirectUrl)
                    /*应用授权作用域，
                    snsapi_base （不弹出授权页面，直接跳转，只能获取用户openid）
                    ，snsapi_userinfo （弹出授权页面，可通过openid拿到昵称、性别、所在地。并且， 即使在未关注的情况下，只要用户授权，也能获取其信息 ）*/
                    .replace("SCOPE", "snsapi_userinfo")
                    /*重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节*/
                    .replace("STATE", "");

    /**
     * 初始化
     *
     * @param map
     * @param request
     * @return
     */
    @GetMapping
    @ResponseBody
    public String accept(Map<String, String> map, HttpServletRequest request) {
        System.err.println(map);
        String signature = request.getParameter("signature");
        String echostr = request.getParameter("echostr");
        String timestamp = request.getParameter("timestamp");
        String nonce = request.getParameter("nonce");
        List<String> list = new ArrayList<>();
        list.add(TOKEN);
        list.add(timestamp);
        list.add(nonce);
        String sha1 =
                SecureUtil.sha1(list.stream().sorted((o1, o2) -> Collator.getInstance(Locale.CHINA).compare(o1, o2)).collect(Collectors.joining()));
        if (sha1.equals(signature)) {
            return echostr;
        }
        return null;
    }

    /**
     * 开发者微信号
     */
    @Value("${wechat.id:}")
    private String wechatId;

    /**
     * 生成返回消息
     *
     * @param openid \
     * @param text   \
     * @return \
     */
    String builderMsg(String openid, String text, String fromUserName) {
        Map<String, String> msgMap = new HashMap<>(16);
        msgMap.put("CreateTime", System.currentTimeMillis() + "");
//        msgMap.put("FromUserName", wechatId);
        msgMap.put("FromUserName", fromUserName);
        msgMap.put("ToUserName", openid);
        msgMap.put("MsgType", "text");
        msgMap.put("Content", text);
        return XmlUtil.mapToXmlStr(msgMap);
    }

    @PostMapping
    @ResponseBody
    public String ask(HttpServletRequest request, HttpServletResponse response) {
        try {
            ServletInputStream inputStream = request.getInputStream();
            Map<String, Object> map = XmlUtil.xmlToMap(IoUtil.read(inputStream, StandardCharsets.UTF_8));
            System.err.println(map);
            Object event = map.get("Event");
            if (event != null) {
                switch (EventTypeEnums.find(event.toString())) {
                    case CLICK:
                        return builderMsg(map.get("FromUserName").toString(), appClickService.doClick(map.get("EventKey").toString()), map.get("ToUserName").toString());
                    case SUBSCRIBE:
                        return builderMsg(map.get("FromUserName").toString(), "感谢关注", map.get("ToUserName").toString());
                    case UNSUBSCRIBE:
                    default:
                }
            }
            else if (map.get("MsgType") != null) {
                return builderMsg(map.get("FromUserName").toString(), "少侠，你发的这些臣妾看不懂呢", map.get("ToUserName").toString());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.err.println(request.getQueryString());
        String openid = request.getParameter("openid");
        return "";
    }

    /**
     * 判断消息类型
     * 取消关注: signature=8a6183fbe3132b0937de233bfd36d631902f3ccb&timestamp=1620657370&nonce=1202153174&openid=oyZpk68QVJRLDdqQ80m6TTKIievw
     * 关注: signature=571e080da5d13fac5c0d6bff760025c510fde8ed&timestamp=1620657508&nonce=1104797153&openid=oyZpk68QVJRLDdqQ80m6TTKIievw
     */
    public int msgType(String msg) {
        return 0;
    }
    private final CommonProperties commonProperties;
    @PostMapping("createButton")
    @ResponseBody
    public String createButton() {

        List<Button> buttons = new ArrayList<>();
        Button button1 = new Button();
        button1.setName("作者发料");
        button1.setType("view");

        button1.setUrl(url.replace("REDIRECT_URI", URLUtil.encode(commonProperties.getDomain()+"?url="+commonProperties.getMenu1(), StandardCharsets.UTF_8)));
        buttons.add(button1);
        Button button2 = new Button();
        button2.setName("粉丝买料");
        button2.setType("view");

        button2.setUrl(url.replace("REDIRECT_URI", URLUtil.encode(commonProperties.getDomain()+"?url="+commonProperties.getMenu2(), StandardCharsets.UTF_8)));
        buttons.add(button2);
        Button button3 = new Button();
        button3.setName("联系客服");
        button3.setType("click");
        button3.setKey("callCustomerService");
        buttons.add(button3);
        Button button = new Button();
        button.setButton(buttons);

        HttpUtil.createPost("https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN".replace("ACCESS_TOKEN", wechatModule.getAccessToken())).body(JSON.toJSONString(button)).execute().close();
        return "ok";
    }

    /**
     * 跳转链接
     *
     * @return
     */
    @GetMapping("getCode")
    public String getCode(String code,String state,String url,HttpServletResponse response) {
        System.err.println(url);
        System.err.println(code);
        HttpUtil.get(GET_ACCESS_TOKEN.replace("CODE", code));
        return url;
    }
//    @GetMapping("getAccessToken")
//    public String getAccessToken(){

//        HttpUtil.get()
//        return null;
//    }
}
